package com.hdoit.pisces.web.home.controllers;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tennetcn.common.aop.CommonApplicationContextUtil;
import com.tennetcn.common.enums.ManageContainer;
import com.tennetcn.common.logical.superbase.model.Business;
import com.tennetcn.common.logical.superbase.model.Employee;
import com.tennetcn.common.logical.superbase.model.Role;
import com.tennetcn.common.logical.superbase.service.IBusinessService;
import com.tennetcn.common.logical.superbase.service.IEmployeeService;
import com.tennetcn.common.logical.superbase.service.IMenuService;
import com.tennetcn.common.logical.superbase.service.IRoleEmployeeService;
import com.tennetcn.common.logical.superbase.service.IRoleService;
import com.tennetcn.common.logical.systask.service.INoticeService;
import com.tennetcn.common.logical.viewmodel.systask.NoticeIndex;
import com.tennetcn.common.logical.viewmodel.systask.NoticeSearch;
import com.tennetcn.common.message.LoginModel;
import com.tennetcn.common.utils.JsonUtils;
import com.tennetcn.common.utils.MD5Utils;
import com.tennetcn.component.intceptor.ILoginedIntceptor;
import com.tennetcn.component.web.ActionResult;
import com.tennetcn.component.web.ErrorResult;
import com.tennetcn.web.cbase.AuthPassport;
import com.tennetcn.web.home.controllers.BaseHomeController;
/** 
 * @author      chenghuan
 * @email       79763939@qq.com
 * @createtime  2016年4月14日
 * @comment 
 */
@Controller
@RequestMapping(value = "/admin/home/")
public class HomeController extends BaseHomeController{
	
private IRoleEmployeeService roleEmployeeService;

private IRoleService roleService;

public IRoleService getRoleService(){
	return roleService;
}

@Resource
public void setRoleService(IRoleService roleService){
	this.roleService = roleService;
}
	
	public IRoleEmployeeService getRoleEmployeeService(){
		return roleEmployeeService;
	}
	
	@Resource
	public void setRoleEmployeeService(IRoleEmployeeService roleEmployeeService){
		this.roleEmployeeService = roleEmployeeService;
	}
	@Override
	public String getRoutePath() {
		return "areas/admin/";
	}	
private INoticeService noticeService;
	
	public INoticeService getNoticeService() {
		return noticeService;
	}
	
	@Resource
	public void setNoticeService(INoticeService noticeService) {
		this.noticeService = noticeService;
	}

	private IEmployeeService employeeService;
	
	public IEmployeeService getEmployeeService() {
		return employeeService;
	}
	
	@Resource
	public void setEmployeeService(IEmployeeService employeeService) {
		this.employeeService = employeeService;
	}
	
	private IMenuService menuService;

	public IMenuService getMenuService() {
		return menuService;
	}
	
	@Resource
	public void setMenuService(IMenuService menuService) {
		this.menuService = menuService;
	}
	
	private IBusinessService businessService;
	
	public IBusinessService getBusinessService() {
		return businessService;
	}

	@Resource
	public void setBusinessService(IBusinessService businessService) {
		this.businessService = businessService;
	}

	//全局请求变量
	private final String indexViewName="index";
	//private final String yindexViewName="yindex";
	private final String mainViewName="main";
	private final String loginViewName = "login";
	private final String logoutViewName="logout";
	private final String noticeListViewName="noticeList";
	//private final String mainnewViewName="mainnew";
	@RequestMapping(value = noticeListViewName, method = { RequestMethod.GET,RequestMethod.POST },produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String notictList(NoticeSearch search){
		search.setLoginId(getLoginModel().getLoginId());
		NoticeIndex noticeIndex=noticeService.queryNoticeIndex(search);
		
		return JsonUtils.writeValueAsString(noticeIndex);
	}
	
	@RequestMapping(value = indexViewName, method = { RequestMethod.GET })
	public String index(Model model){
		return view(indexViewName);
	}
	
//	@RequestMapping(value = yindexViewName, method = { RequestMethod.GET })
//	public String yindex(Model model){
//		return view(yindexViewName);
//	}
	
//	@RequestMapping(value = mainnewViewName, method = { RequestMethod.GET })
//	public String mainnew(Model model){
//		return view(mainnewViewName);
//	}
	@RequestMapping(value = mainViewName, method = { RequestMethod.GET })
	public String main(){
		return view(mainViewName);
	}
	
	@RequestMapping(value =loginViewName, method = { RequestMethod.GET })
	@AuthPassport
	public String login() {
		return loginViewName;
	}
	
	@RequestMapping(value =loginViewName, method = { RequestMethod.POST })
	@AuthPassport
	public String login(Model model,String imgNum,String rememberPassword,String login_username,String login_password,HttpServletResponse response) {
		
		ActionResult actionResult=new ErrorResult();
		model.addAttribute("imgNum", imgNum);
		//为空的验证
		if(StringUtils.isEmpty(login_username)||StringUtils.isEmpty(login_password)){
			actionResult.setMessage("用户名和密码不能为空");
			model.addAttribute(ManageContainer.RESULTKEY,actionResult);
			return loginViewName;
		}
		String md5Pass=MD5Utils.encoderByMd5With32Bit(login_password);
		if(!StringUtils.isEmpty(rememberPassword)&&rememberPassword.length()==32){
			md5Pass=rememberPassword;
		}
		LoginModel loginModel= loginValid(login_username,md5Pass);
		if(loginModel==null){
			actionResult.setMessage("用户名或密码错误");
			model.addAttribute(ManageContainer.RESULTKEY,actionResult);
			return loginViewName;
		}
		
		List<Role> roles=roleService.queryList(loginModel.getLoginId());
		loginModel.setArgument(ManageContainer.SESSION_ARUMENT_ROLES, roles);
		
		Business business=businessService.queryModelByLoginId(loginModel.getLoginId());
		loginModel.setArgument(ManageContainer.SESSION_ARUMENT_BUSINESS, business);
		
		sessionWebFactory.setCurrentLogin(loginModel);
		
		try {
			boolean responseAgain=true;
			try{
				ILoginedIntceptor loginedIntceptor=CommonApplicationContextUtil.getCurrentContext().getBean(ILoginedIntceptor.class);
				if(loginedIntceptor!=null){
					responseAgain=loginedIntceptor.loginedExec(loginModel, response);
				}else{
					responseAgain=logined(loginModel,response);
				}
			}catch(Exception ex){
				responseAgain=logined(loginModel,response);
			}
			if(responseAgain){
				//String key="1";
				String id=getLoginModel().getLoginId();
				//System.out.println(id);
				//System.out.println(roleEmployeeService);
				List<String> role=roleEmployeeService.queryRoleIdsByEmployeeId(id);
				
				//System.out.println(role.size());
				//System.out.println(role);
				List<String> rerole=roleService.queryListStringByMark("3");
				//System.out.println(rerole.size());
				//System.out.println(rerole);
				if(role.get(0).equals(rerole.get(0))){
					//response.sendRedirect(ManageContainer.VIRTUALPATH+"/admin/home/yindex");
					response.sendRedirect(ManageContainer.VIRTUALPATH+"/admin/mainnew");
				}else{
					response.sendRedirect(ManageContainer.VIRTUALPATH+"/admin/home/index");
				}
				
			
				
			}
		} catch (IOException e) {
			actionResult.setMessage(e.getMessage());
		}

		model.addAttribute(ManageContainer.RESULTKEY,actionResult);
		
		return loginViewName;
	}
	
	private LoginModel loginValid(String username,String password){
		Employee employee=null;
		LoginModel login=null;
		int tryCount=5;
		
		do{
			//检测判断，如果login报错
			//判断有没有可能是CannotCreateTransactionException的错误
			//进行尝试连接，如果连续5次还是不行就不判断了
			try{
				employee= employeeService.login(username, password);
				tryCount=0;
			}catch(Exception e){
				login=new LoginModel();
				tryCount--;
			}
		}while(tryCount>0);
		
		if(employee==null){return login;}
		
		login=new LoginModel();
		login.setLoginId(employee.getEmployeeId());
		login.setLoginAccount(employee.getEmployeeAccount());
		login.setLoginName(employee.getEmployeeName());
		login.setLoginPass(employee.getEmployeePass());
		

		return login;
	}
	

	@RequestMapping(value = logoutViewName, method = { RequestMethod.GET })
	public String logout(Model model,String quitMode,HttpServletResponse response){
		sessionWebFactory.clearCurrentLogin();
		try {
			response.sendRedirect(ManageContainer.VIRTUALPATH+"/admin/home/login");
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return login();
	}
		
	protected boolean logined(LoginModel loginModel,HttpServletResponse response){
		return true;
	}
}
